package com.tmt.im.manager.service;

import com.tmt.im.common.pojo.IMFriendGroupPoJo;
import com.tmt.im.jpa.repository.IMFriendGroupRepo;
import com.tmt.im.manager.controller.vo.FriendGroupInfoVo;
import com.tmt.im.manager.controller.vo.NewFriendGroupRequest;
import com.tmt.im.manager.controller.vo.UpdateFriendGroupRequest;
import com.tmt.im.manager.helper.IgniteQueryHelper;
import com.tmt.im.manager.helper.PrincipalHelper;
import com.tmt.im.manager.mapstruct.IMFriendGroupMapStruct;
import com.tmt.springboot.common.helper.IdSnowFlake;
import com.tmt.springboot.common.restful.ExecuteResult;
import com.tmt.springboot.common.restful.IExecuteResult;
import org.apache.ignite.Ignite;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.security.Principal;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/8/24 17:42
 * @Version 1.0
 **/
@Service
public class IMFriendGroupIgniteService extends BaseService {

    private final IMFriendGroupMapStruct imFriendGroupMapStruct;

    public IMFriendGroupIgniteService(Ignite ignite,
                                      IMFriendGroupMapStruct imFriendGroupMapStruct) {
        super(ignite);
        this.imFriendGroupMapStruct = imFriendGroupMapStruct;
    }

    public IExecuteResult<Boolean> addFriendGroup(NewFriendGroupRequest request, Principal principal) {
        Long currentUserId = PrincipalHelper.getCurrentUserId(principal);
        try {
            IMFriendGroupPoJo group = IMFriendGroupPoJo.builder()
                    .id(IdSnowFlake.getId())
                    .name(request.getName())
                    .note(request.getNote())
                    .creatorId(currentUserId)
                    .version(0L)
                    .createTime(new Timestamp(System.currentTimeMillis()))
                    .insert(true)
                    .build();
            friendGroupCache.put(group.getKey(), group);
        } catch (Exception ex) {
            return ExecuteResult.failure(ex.getMessage(), false);
        }
        return ExecuteResult.success(true);
    }

    public IExecuteResult<Boolean> updateFriendGroup(UpdateFriendGroupRequest request, Principal principal) {
        Long currentUserId = PrincipalHelper.getCurrentUserId(principal);
        try {
            IMFriendGroupPoJo group = friendGroupCache.get(request.getId());
            if (group == null) {
                return ExecuteResult.failure("目标好友分组不存在", false);
            }
            if (!Objects.equals(group.getCreatorId(), currentUserId)) {
                return ExecuteResult.failure("不能修改他人的好友分组", false);
            }
            if (StringUtils.hasText(request.getName())) {
                group.setName(request.getName());
            }
            if (StringUtils.hasText(request.getNote())) {
                group.setNote(request.getNote());
            }
            group.setVersion(group.getVersion() + 1);
            group.setInsert(false);
            friendGroupCache.put(group.getKey(), group);
        } catch (Exception ex) {
            return ExecuteResult.failure(ex.getMessage(), false);
        }
        return ExecuteResult.success(true);
    }

    public IExecuteResult<List<FriendGroupInfoVo>> listFriendGroup(Principal principal) {
        Long currentUserId = PrincipalHelper.getCurrentUserId(principal);
        String sql = MessageFormat.format("select * from {0} where creatorId = ?", IMFriendGroupPoJo.CACHE_NAME);
        List<IMFriendGroupPoJo> friendGroupPoJos = IgniteQueryHelper.findAllBy(sql, new Object[]{currentUserId},
                IMFriendGroupPoJo.class, friendGroupCache);
        List<FriendGroupInfoVo> voList = imFriendGroupMapStruct.toFriendGroupInfoVos1(friendGroupPoJos);
        return ExecuteResult.success(voList);
    }

    public IExecuteResult<Boolean> deleteFriendGroup(Long groupId, Principal principal) {
        Long currentUserId = PrincipalHelper.getCurrentUserId(principal);
        IMFriendGroupPoJo groupPoJo = friendGroupCache.get(groupId);
        if (groupPoJo == null) {
            return ExecuteResult.failure("目标好友分组不存在", false);
        }
        if (!Objects.equals(groupPoJo.getCreatorId(), currentUserId)) {
            return ExecuteResult.failure("不能删除他人的好友分组", false);
        }
        friendGroupCache.remove(groupId);
        return ExecuteResult.success(true);
    }
}
